<template>
    <el-input   :class="['custom-input']"
                v-model="value"
                :clearable="clearable"
                @change="emit('change', $event)"
                @input="handleInput" @blur="handleBlur"
                :readonly="readonly"
                :maxlength="maxlength"
    >
    </el-input>
</template>
<script lang="ts" setup>
import { defineProps, watch, withDefaults, ref } from 'vue';
const props = withDefaults(defineProps<{
    modelValue: string | number | null,
    clearable?: boolean,
    readonly?: boolean,
    maxlength?: number,
    type: string
}>(), {
    min: 0,
    precision: 0,
    fixPrecision: false,
    isBlank: false,
    readonly: false,
});

const value = ref<string|number>(props.modelValue);
const emit = defineEmits(['update:modelValue', 'change', 'blur']);


watch(() => props.modelValue, (n, o) => {
    if (n && n.toString() !== o) {
        value.value = allowPlus(n.toString(), props.precision);
        emit('update:modelValue', value.value);
    } else {
        value.value = '';
        emit('update:modelValue', value.value);
    }
}, { immediate: true });

watch(() => value.value, (n, o) => {
    value.value = n;
    emit('update:modelValue', n);
});

function  allowPlus($event:string) {
    if (props.type === 'englishNumber') {
        return $event.replace(/[^\w]/ig, '');
    }
    if (props.type === 'phone') {
        return $event.replace(/[^\d]/ig, '');
    }
};

function handleInput($event:string) {
    value.value = allowPlus($event, props.precision);
    emit('update:modelValue', value.value);
}

function handleBlur() {
    emit('blur');
}
</script>
<style lang="less" scoped>
.custom-input {
    /deep/ .md-input-group__append {
        padding: 0px 10px;
    }
}

.number-input-left {
    /deep/ .md-input__inner {
        text-align: left;
    }
}
</style>